package ListNodePractice;

public class RotateList {
    /**
     * 旋转链表
     * 给你一个链表的头节点 head ，旋转链表，将链表每个节点向右移动k个位置。
     * <p>
     * <p>
     * 示例 1：
     * <p>
     * <p>
     * 输入：head = [1,2,3,4], k = 1
     * 1,2,3,4,1,2,3,4
     * 4123
     * 输出：[4,5,1,2,3]
     * 示例 2：
     * <p>
     * <p>
     * 输入：head = [0,1,2], k = 4
     * 输出：[2,0,1]
     */

    public static ListNode rotateRight(ListNode head, int k) {
        if (k == 0 || head == null || head.next == null) {
            return null;
        }
        ListNode temp = head;
        int len = 1;
        while (temp.next != null) {
            temp = temp.next;
            len++;
        }
        int add = len - k % len;
        if (add == 0) {
            return head;
        }
        temp.next = head;
        while (add > 0) {
            add --;
            temp = temp.next;
        }
        //temp = 3
        //temp.next = 4;
        //resultList = 4;
        ListNode resultList = temp.next;
        //3.next == null 从三这块断开
        temp.next = null;
        return resultList;
    }

    public static void main(String[] args) {
        ListNode l11 = new ListNode(1);
        ListNode l12 = new ListNode(2);
        ListNode l13 = new ListNode(3);
        ListNode l14 = new ListNode(4);
        l11.next = l12;
        l12.next = l13;
        l13.next = l14;
        ListNode listNode = rotateRight(l11, 1);
        System.out.println(listNode);
    }
}
